//
//  HJCustomerReceptionViewController.m
//  GAMCAfterSales
//
//  Created by 贺佳 on 2018/5/17.
//  Copyright © 2018年 glendale. All rights reserved.
//

#import "HJCustomerReceptionViewController.h"
#import "getJobSheetViewController.h"


#import "HJCustomerReceptionSearchView.h"
#import "HJCustomerReceptionViewCell.h"

#import "HJCustomerReceptionModel.h"

#import <AipOcrSdk/AipOcrSdk.h>
#import "AFNetworking.h"
#import "UIImagePickerController+HJLandScapeImagePicker.h"

@interface HJCustomerReceptionViewController ()<HJCustomerReceptionSearchViewDelegate,UIActionSheetDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/**
 table头标题
 */
@property(nonatomic,weak)HJCommonTableHeaderView*headerView;
/**
 搜索视图
 */
@property(nonatomic,weak)HJCustomerReceptionSearchView*searchView;
/**
 tableView
 */
@property(nonatomic,strong)UITableView*tableView;
/**
下单按钮
 */
@property(nonatomic,weak)UIButton*placeOrderBtn;
/**
 数据源
 */
@property(nonatomic,strong)NSArray*dataAry;
/**
 用户选择行
 */
@property(nonatomic,strong)NSIndexPath*selectIndexPath;
/**
 搜索关键字
 */
@property(nonatomic,copy)NSString*key;
/**
 相册控制器
 */
@property(nonatomic,strong)UIImagePickerController *imagePicker;
/**
 是否自动刷新
 */
@property(nonatomic,assign)BOOL isRefresh;
@end

@implementation HJCustomerReceptionViewController

-(UIImagePickerController *)imagePicker
{
    if(!_imagePicker){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        _imagePicker=picker;
    }
    return _imagePicker;
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.tableFooterView=[UIView new];
//        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        WEAKSELF;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(weakSelf.headerView);
            make.bottom.mas_equalTo(weakSelf.placeOrderBtn.mas_top).inset(15);
            make.top.mas_equalTo(weakSelf.headerView.mas_bottom);
        }];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRefresh=YES;
    [self setUI];
    
    //授权百度
//     [[AipOcrService shardService] authWithAK:@"ENwKPNbuCpEg8wGa9WVvUz5d" andSK:@"wD9fGQUmUXafRofd9pwf75sawVjTrmes"];
    
    NSString *licenseFile = [[NSBundle mainBundle] pathForResource:@"aip" ofType:@"license"];
        NSData *licenseFileData = [NSData dataWithContentsOfFile:licenseFile];
        if(!licenseFileData) {
            [[[UIAlertView alloc] initWithTitle:@"授权失败" message:@"授权文件不存在" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        }
        [[AipOcrService shardService] authWithLicenseFileData:licenseFileData];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.isRefresh) {
        [self searchOrder:self.key];
    }
    self.isRefresh=YES;
//
}
-(void)setUI{
    self.view.backgroundColor=[UIColor whiteColor];
    //返回按钮
    UIButton*homeBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage*img=[UIImage imageNamed:@"房子.png"];
    [homeBackButton setImage:img forState:UIControlStateNormal];
    CGFloat h=40;
    CGFloat w=h/img.size.height*img.size.width;
    [homeBackButton setFrame:CGRectMake(60, 42, w, h)];
    [homeBackButton addTarget:self action:@selector(InformatBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:homeBackButton];
    
    //视图标题
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(200, 45, 200, 40)];
    titleLabel.text = @"客户接待";
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont systemFontOfSize:30];
    [self.view addSubview:titleLabel];
    
    UIImageView *lineView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 100, 1000, 11)];
    lineView.image = [UIImage imageNamed:@"渐变分割线.png"];
    [self.view addSubview:lineView];
    
    WEAKSELF;
    //条件视图
    HJCustomerReceptionSearchView*searchView=[[HJCustomerReceptionSearchView alloc]init];
    searchView.layer.cornerRadius=10;
    searchView.layer.borderWidth=1.5;
    searchView.layer.borderColor=[UIColor grayColor].CGColor;
    self.searchView=searchView;
    searchView.layer.masksToBounds=YES;
    [self.view addSubview:searchView];
    searchView.delegate=self;
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(700, 80));
        make.top.mas_equalTo(lineView.mas_bottom).offset(30);
        make.centerX.mas_equalTo(weakSelf.view);
    }];
    //table头
    NSMutableArray *labelMutabelArray = [[NSMutableArray alloc]initWithObjects:@"序号",@"车牌号",@"车架号",@"车系",@"车型",@"车主姓名",@"车主手机", nil];
    HJCommonTableHeaderView*headerView=[[HJCommonTableHeaderView alloc]init];
    headerView.titleAry=[labelMutabelArray copy];
    self.headerView=headerView;
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(lineView).inset(60);
        make.top.mas_equalTo(searchView.mas_bottom).offset(50);
        make.height.mas_equalTo(45);
    }];
    
    //开单按钮
    UIButton*placeOrderBtn=[[UIButton alloc]init];
    [self.view addSubview:placeOrderBtn];
    self.placeOrderBtn=placeOrderBtn;
    placeOrderBtn.backgroundColor=[UIColor redColor];
    [placeOrderBtn setTitle:@"下单" forState:UIControlStateNormal];
    placeOrderBtn.layer.cornerRadius=8;
    placeOrderBtn.layer.masksToBounds=YES;
    [placeOrderBtn addTarget:self action:@selector(clickPlaceOrder) forControlEvents:UIControlEventTouchUpInside];
    [placeOrderBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 35));
        make.right.mas_equalTo(searchView);
        make.bottom.mas_equalTo(weakSelf.view).inset(50);
    }];
}
-(void)InformatBack{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)clickPlaceOrder{
   
    if (self.dataAry.count) {
        [self gotoWorkOrderVc];
    }
}
#pragma mark --HJCustomerReceptionSearchViewDelegate
-(void)customerReceptionSearchView:(HJCustomerReceptionSearchView *)customerReceptionSearchView clickSearchNumber:(NSString *)number
{
    self.key=number;
    [self searchOrder:number];
}
-(void)searchOrder:(NSString*)key{
    
    if (!key) {
        return;
    }
       key =  [[NSString stringWithFormat:@"%@",key]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [SVProgressHUD showWithStatus:@"查询中，请稍后..."];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSDictionary * params = @{
                              @"ENTITY_CODE":[user objectForKey:@"ENTITY_CODE"],
                              @"VIN_OR_LICENSE":key};//key
    //api调用及返回
    WEAKSELF;
    [MyAFNetWorkManager postWithParam:params andAction:@"CUSTOMER_RECEPTION_FOR_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error == nil)
        {
            NSLog(@"客户接待 json is %@",obj);
            if ([obj[@"SUCCESS"] integerValue]==1) {
                NSArray*ary=[HJCustomerReceptionModel mj_objectArrayWithKeyValuesArray:obj[@"TM_VEHICLE_OWNER"]];
                weakSelf.dataAry=[ary copy];
//                weakSelf.dataAry=@[ary[1]];
                [weakSelf.tableView reloadData];
                
               
                if (weakSelf.dataAry.count) {
                    //默认选择第一行
                    NSIndexPath*indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
                     [weakSelf.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
                    [weakSelf tableView:weakSelf.tableView didSelectRowAtIndexPath:indexPath];
                }
               
                if (weakSelf.dataAry.count==1) {
                    //直接下单
                    [weakSelf gotoWorkOrderVc];
                }
               
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}
-(void)customerReceptionSearchViewClickScan:(HJCustomerReceptionSearchView *)customerReceptionSearchView
{
    WEAKSELF;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES; //可编辑
    //判断是否可以打开照相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //摄像头
        //UIImagePickerControllerSourceTypeSavedPhotosAlbum:相机胶卷
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    } else { //否则打开照片库
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [self presentViewController:picker animated:YES completion:nil];
    
//    UIViewController * vc = [AipGeneralVC ViewControllerWithHandler:^(UIImage *image) {
//        NSDictionary*options=@{@"detect_direction":@"true"};
//        [[AipOcrService shardService] detectPlateNumberFromImage:image withOptions:options successHandler:^(id result){
//
//            // 在成功回调中，保存图片到系统相册
//            //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, (__bridge void *)self);
//            // 打印出识别结果
//
//            NSLog(@"%@", result);
//
//            NSString*number=result[@"words_result"][@"number"];
//            [weakSelf searchOrder:number];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [SVProgressHUD dismiss];
//                weakSelf.key=number;
//                weakSelf.searchView.key=number;
//                [weakSelf dismissViewControllerAnimated:YES completion:nil];
//            });
//
//            NSLog(@"%@", result);
//
//        }failHandler:^(NSError *err) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                     ALERT(@"识别失败");
//                     [weakSelf dismissViewControllerAnimated:YES completion:nil];
//
//                });
//            }];
//
//    }];
//    [self presentViewController:vc animated:YES completion:nil];

}

-(NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280) {
        if (width>height) {
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }else{
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }
        //2.高度大于1280
    }else if(height>1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
             data=UIImagePNGRepresentation(newImage);
//            data=UIImagePNGRepresentation(newImage); UIImageJPEGRepresentation(newImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
             data=UIImagePNGRepresentation(newImage);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImagePNGRepresentation(newImage);
        }
    }
    return data;
}

#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //
    return self.dataAry.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HJCustomerReceptionViewCell*cell=[HJCustomerReceptionViewCell cellWithTable:tableView];
    cell.customerReceptionModel=self.dataAry[indexPath.row];
    cell.indexPath=indexPath;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if(indexPath.row%2 == 1)
//    {
//        cell.backgroundColor = [[UIColor alloc]initWithRed:226.00/255 green:226.00/255 blue:226.00/255 alpha:1];
//    }
//    else
//    {
//        cell.backgroundColor = [UIColor whiteColor];
//    }
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectIndexPath=indexPath;
}
-(void)gotoWorkOrderVc{
   MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    NSInteger index=self.selectIndexPath.row;
    HJCustomerReceptionModel*customerReceptionModel=self.dataAry[index];
     NSDictionary *param = @{@"VIN":customerReceptionModel.VIN,@"STATE_NAME":@"12551001"};
    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF;
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_DETAIL_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
            return;
        }else{
            getJobSheetViewController *getJobSheetCon = [[getJobSheetViewController alloc] initWithNibName:@"getJobSheetViewController" bundle:nil];
            getJobSheetCon.returnBack = ^{
                self.isRefresh=NO;
            };
//            NSMutableArray *arr = obj[@"TM_VEHICLE"];//预交款
//            NSDictionary *predic = arr[0];
                mainModel.dicBaseMessage = customerReceptionModel.mj_keyValues;
                mainModel.arrOutCheck = nil;//缺陷
                mainModel.repairProjects = nil;//维修项目
                mainModel.partList = nil;//零件
                mainModel.attachProjects = nil;//附加项目
                mainModel.arrCarryGoods = nil;//物品确认
                mainModel.arrImageList = nil;//图片列表
                getJobSheetCon.optType = operationTypeAdd;
            mainModel.deletedRepairProjects = nil;
            mainModel.deletedPartList = nil;
            mainModel.deletedAttachProjects = nil;
            mainModel.arrOutCheckDeleted = nil;
            mainModel.nRowForRepairItemList = -1;
            mainModel.nRowForPartList = -1;
            mainModel.nRowForOtherChargeList = -1;
            mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
            picDataModel.arrForNewImage = nil;
            [weakSelf.navigationController pushViewController:getJobSheetCon animated:YES];
        }
    }];
}
#pragma mark - UIImagePickerControllerDelegate

//拍摄完成后要执行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    WEAKSELF;
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSDictionary*options=@{@"detect_direction":@"true"};
    [SVProgressHUD showWithStatus:@"正在识别"];
            [[AipOcrService shardService] detectPlateNumberFromImage:image withOptions:options successHandler:^(id result){
                // 在成功回调中，保存图片到系统相册
                //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, (__bridge void *)self);
                // 打印出识别结果
    
                NSLog(@"%@", result);
    
                NSString*number=result[@"words_result"][@"number"];
                [weakSelf searchOrder:number];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    weakSelf.key=number;
                    weakSelf.searchView.key=number;
                    [weakSelf dismissViewControllerAnimated:YES completion:nil];
                });
    
                NSLog(@"%@", result);
    
            }failHandler:^(NSError *err) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                         ALERT(@"识别失败");
                         [weakSelf dismissViewControllerAnimated:YES completion:nil];
    
                    });
                }];
    
//    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
